package com.idbk.chargestation.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.pile.ActivityPointDetail;
import com.idbk.chargestation.activity.pile.ActivityReservePile;
import com.idbk.chargestation.adapter.PileAdapter;
import com.idbk.chargestation.adapter.TJDropdownAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.bean.JsonPoint;
import com.idbk.chargestation.bean.JsonPointPile;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.FlagRequest;
import com.idbk.chargestation.util.GsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 电桩Fragment
 *
 * @author liangzw, lupc
 */
public class FragmentPiles extends Fragment implements OnClickListener {

    private Context mContext;

    private View mView;

    private TextView mTextPileInfor, mBook;

    private SwipeRefreshLayout mSwipeRL;
    private ListView mListView;

    private List<JsonPointPile> mData;
    private PileAdapter mAdapter;

    private JsonPoint mResult;

    private LinearLayout mLayoutEmpty;
    private boolean isHavePile = true;

    private int mPointId;
    private int userRole;

    private LinearLayout mLinearBook;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_piles, container, false);

        mContext = getActivity();

        setupView();

        setupData();

        return mView;
    }

    private void setupView() {
        mLinearBook = (LinearLayout) mView.findViewById(R.id.linear_booked);
        mSwipeRL = (SwipeRefreshLayout) mView.findViewById(R.id.swipeRL);
        mSwipeRL.setColorSchemeResources(R.color.tj_theme);

        mTextPileInfor = (TextView) mView.findViewById(R.id.textview_pile_filter);
        mTextPileInfor.setOnClickListener(this);
        mLayoutEmpty = (LinearLayout) mView.findViewById(R.id.tj_empty_view);

        mListView = (ListView) mView.findViewById(R.id.listview);
        mData = new ArrayList<JsonPointPile>();
        mAdapter = new PileAdapter(mContext, mData, mListView);
        mListView.setAdapter(mAdapter);

        mBook = (TextView) mView.findViewById(R.id.textview_book);
        mBook.setOnClickListener(this);

        mSwipeRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                ChargeStationAPI.getPointDetail(mPointId, mResponse);
            }
        });

        userRole = AppContext.getInstance().getUserRole();
        if (userRole == 2){
            mLinearBook.setVisibility(View.GONE);
        }else {
            mLinearBook.setVisibility(View.VISIBLE);
        }
    }

    private void setupData() {
        mPointId = getArguments().getInt(Const.KEY_ID);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            JsonPoint result = GsonUtils.toBean(JsonPoint.class, response);
            notifyDataCallback(result);
        }

        @Override
        public void onEFinish() {
            super.onEFinish();
            mSwipeRL.setRefreshing(false);
        }

    };

    public void notifyDataCallback(JsonPoint result) {
        mResult = result;

        if (result != null && result.pointDetails != null) {
            mTextPileInfor.setText("全部电桩（" + result.pointDetails.size() + "）");
            if (getActivity() != null) {
                ((ActivityPointDetail) getActivity()).setPileCount(result.total, result.idleNum);
            }
            mData.clear();
            if (result.pointDetails.size() == 0) {
                mBook.setBackgroundResource(R.drawable.bg_main_button_sm_black);
                mLayoutEmpty.setVisibility(View.VISIBLE);
                mListView.setVisibility(View.GONE);
                isHavePile = false;
            } else {
                mLayoutEmpty.setVisibility(View.GONE);
                mBook.setBackgroundResource(R.drawable.bg_main_button_lg_sprite_2);
                mListView.setVisibility(View.VISIBLE);
                mData.addAll(result.pointDetails);
                isHavePile = true;
            }
        } else {
            mTextPileInfor.setText("全部电桩（0）");
            mBook.setBackgroundResource(R.drawable.bg_main_button_sm_black);
            isHavePile = false;
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.textview_book) {
            reservePile();
        } else if (v.getId() == R.id.textview_pile_filter) {
            showFilterView();
        }
    }

    private void showFilterView() {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.listview_for_tj_dropdown,
                new LinearLayout(mContext), false);
        ListView lv = (ListView) view.findViewById(R.id.listview);

        final TJDropdownAdapter adapter = new TJDropdownAdapter(mContext, PILE_STATE_FILTER);
        adapter.setSelectedItemIndex(mIndexFilter);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                adapter.setSelectedItemIndex(position);
                adapter.notifyDataSetChanged();
                mIndexFilter = position;
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                //执行过滤
                doPointFilter();
            }
        });

        showViewWithPopWindow(view, 0);
    }


    private int mIndexFilter;
    private PopupWindow mPopWindow;
    private final static String[] PILE_STATE_FILTER = new String[]{
            "全部电桩",
            "空闲电桩",
            "可预约",
    };

    private void showViewWithPopWindow(final View view, final int index) {
        mPopWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        });

        mPopWindow.setFocusable(true);
        mPopWindow.setOutsideTouchable(true);
        mPopWindow.setBackgroundDrawable(new PaintDrawable(Color.argb(99, 99, 99, 99)));
        mPopWindow.showAsDropDown(mTextPileInfor, 0, 0);
    }

    private void doPointFilter() {
        if (mIndexFilter == 0) {
            //显示全部
            mData.clear();
            if (mResult != null && mResult.pointDetails != null) {
                mData.addAll(mResult.pointDetails);
                mTextPileInfor.setText("全部电桩（" + mResult.pointDetails.size() + "）");
            }
            mAdapter.notifyDataSetChanged();
        } else if (mIndexFilter == 1) {
            //显示空闲
            mData.clear();
            for (JsonPointPile msg : mResult.pointDetails) {
                if (msg.pileStatue == JsonPointPile.STATUS_IDLE) {
                    mData.add(msg);
                }
            }
            mAdapter.notifyDataSetChanged();
            mTextPileInfor.setText("空闲电桩（" + mData.size() + "）");
        } else if (mIndexFilter == 2) {
            //显示可预约
            mData.clear();
            for (JsonPointPile msg : mResult.pointDetails) {
                if (msg.bookAvailable && msg.pileStatue == JsonPointPile.STATUS_IDLE) {
                    mData.add(msg);
                }
            }
            mAdapter.notifyDataSetChanged();
            mTextPileInfor.setText("可预约（" + mData.size() + "）");
        }
    }

    private void reservePile() {
        if (isHavePile) {
            Intent intent = new Intent(mContext, ActivityReservePile.class);
            intent.putExtra(Const.KEY_ID, mResult.id);
            startActivityForResult(intent, FlagRequest.REQUEST_RESERVE_PILE);
        } else {
            Snackbar.make(mBook, "当前没有可选择的电桩", Snackbar.LENGTH_LONG).show();
        }

    }

}
